package com.aduerr.v1shouyin.mvp.base;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.widget.Toast;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

/**
 *
 */

public abstract class BaseObserver<T> implements Observer {
    private static final String TAG = "BaseObserver";
    SweetAlertDialog pDialog;
    private T t;
    private Context mContext;

    public BaseObserver(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        pDialog = new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#005fee"));
        pDialog.setTitleText("正在加载");
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    public void onNext(@NonNull Object o) {
        onResponse((T) o);
        Log.i(TAG, "onNext: " + o.toString());
    }

    @Override
    public void onError(@NonNull Throwable e) {
        Log.i(TAG, "onError: " + e.toString());
        if(e instanceof SocketTimeoutException) {
            Toast.makeText(mContext, "网络连接超时", Toast.LENGTH_SHORT).show();
        } else if(e instanceof ConnectException) {
            Toast.makeText(mContext, "连接失败", Toast.LENGTH_SHORT).show();
        } else {
            Log.e("onError:", "error:" + e.getMessage());//R.string.checknet +
            Toast.makeText(mContext, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
        }
        Log.i(TAG, "onError: " + e.toString());
        pDialog.dismiss();
        pDialog = null;
    }

    @Override
    public void onComplete() {
        pDialog.dismiss();
        pDialog = null;
    }

    /**
     * 抽象方法 重写后调用请求结果
     *
     * @param t
     */
    public abstract void onResponse(@NonNull T t);
}
